package com.hll.filter;

import com.hll.pojo.User;
import com.hll.utils.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 后台直接访问过滤器
 *
 * @author: Mr.Hu
 * @create: 2021-03-07 21:56
 */
public class AccessFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}

  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    // 不转换,有些方法用不了
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
    if (null != user) {
      filterChain.doFilter(servletRequest, servletResponse);
    } else { // 未登入
      response.sendRedirect(request.getContextPath() + "/login.jsp");
    }
  }

  @Override
  public void destroy() {}
}
